<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>计数器</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #2F80ED;
            --success: #27AE60;
            --danger: #EB5757;
            --background: #F8F9FA;
            --surface: #FFFFFF;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--background);
            margin: 0;
            padding: 24px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        .input-group {
            display: flex;
            gap: 16px;
            margin-bottom: 32px;
        }

        input {
            flex: 1;
            padding: 16px;
            border: 2px solid #E0E0E0;
            border-radius: 12px;
            font-size: 16px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            background: var(--primary);
            color: white;
        }

        .counter-card {
            background: var(--surface);
            border-radius: 16px;
            padding: 24px;
            margin-bottom: 16px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        }

        .count-display {
            font-size: 48px;
            font-weight: 800;
            color: var(--primary);
        }

        .control-group {
            display: flex;
            gap: 16px;
            align-items: center;
        }

        .control-btn {
            width: 56px;
            height: 56px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            font-size: 24px;
        }

        .plus-btn { background: var(--success); color: white; }
        .minus-btn { background: var(--danger); color: white; }

        /* 新增清除区域样式 */
        .danger-zone {
            margin-top: 40px;
            padding: 20px;
            background: #fff3f3;
            border-radius: 12px;
            border: 2px solid #ffebee;
        }

        .clear-btn {
            background: #ff4444;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .clear-btn:hover {
            background: #cc0000;
            transform: translateY(-2px);
        }

         /* 绩效统计样式 */
         .performance-summary {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        }

        .performance-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }

        .performance-item:last-child {
            border-bottom: none;
        }

        .performance-label {
            color: #666;
        }

        .performance-value {
            font-weight: 500;
        }

        .performance-value.good {
            color: #27AE60;
        }

        .performance-value.bad {
            color: #EB5757;
        }

        .danger-zone {
            margin-top: 40px;
            padding: 20px;
            background: #fff3f3;
            border-radius: 12px;
            border: 2px solid #ffebee;
        }

        .danger-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-bottom: 12px;
        }

        .clear-btn {
            background: #EB5757;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
            border: none;
            font-family: inherit;
        }

        .clear-btn:hover {
            background: #c53030;
            transform: translateY(-2px);
        }

        .danger-tip {
            color: #EB5757;
            margin: 8px 0 0;
            font-size: 0.9em;
            text-align: center;
        }

                /* 新增删除按钮样式 */
        .delete-btn {
            background: none;
            border: none;
            color: var(--danger);
            cursor: pointer;
            padding: 6px;
            border-radius: 6px;
            transition: all 0.2s;
        }

        .delete-btn:hover {
            background: #ffebee;
            transform: scale(1.1);
        }

        .delete-btn:active {
            transform: scale(0.95);
        }

        /* 阈值控件样式 */
        .threshold-control {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .threshold-input {
            width: 80px;
            padding: 8px 12px;
            border: 2px solid #E0E0E0;
            border-radius: 8px;
            font-family: inherit;
            font-size: 14px;
            transition: all 0.2s;
        }

        .threshold-input:focus {
            border-color: var(--primary);
            outline: none;
            box-shadow: 0 0 0 3px rgba(47, 128, 237, 0.1);
        }

        .threshold-unit {
            color: #666;
            font-size: 0.9em;
        }

        /* 新增错误状态提示样式 */
.performance-value {
    font-weight: bold;
}
.performance-value.good {
    color: #28a745;
}
.performance-value.bad {
    color: #dc3545;
}
        
    </style>
</head>
<body>
    <div class="container">
        <div class="input-group">
            <input type="text" 
                   id="accountName" 
                   placeholder="输入游戏账号名称">
            <button class="btn" onclick="addAccount()">
                <i class="fas fa-plus"></i> 添加账号
            </button>
        </div>

        <div id="countersContainer"></div>

    <!-- 在统计面板中添加容器值显示 -->
<div class="performance-summary" id="statsPanel">
    <div class="performance-item">
        <span class="performance-label">总对话数：</span>
        <span class="performance-value" id="totalCount">0</span>
    </div>
    <div class="performance-item">
        <span class="performance-label">可用补偿值：</span>
        <span class="performance-value" id="compensationValue">0</span>
    </div>
    <div class="performance-item">
        <span class="performance-label">容器值：</span>
        <span class="performance-value" id="containerValue">-100</span>
    </div>
    <div class="performance-item">
        <span class="performance-label">目标阈值：</span>
        <div class="threshold-control">
            <input type="number" 
                 id="thresholdInput" 
                 min="1" 
                 value="100"
                 class="threshold-input">
            <span class="threshold-unit">次/账号</span>
        </div>
    </div>
</div>

</div>

        <!-- 安全清除区域 -->
        <div class="danger-zone">
            <div class="danger-buttons">
                <button class="clear-btn" onclick="resetAllCounters()">
                    <i class="fas fa-undo-alt"></i>
                    一键清零所有计数
                </button>
                <button class="clear-btn" onclick="handleClearAll()">
                    <i class="fas fa-exclamation-triangle"></i>
                    清除所有数据
                </button>
            </div>
            <p class="danger-tip">⚠️ 危险操作：这些操作不可逆，请谨慎使用！</p>
        </div>
    </div>

   <script>
    // 数据初始化
    let counters = JSON.parse(localStorage.getItem('chatCounters')) || {};

    // 阈值初始化
    let currentThreshold = parseInt(localStorage.getItem('chatThreshold')) || 100;
    document.getElementById('thresholdInput').value = currentThreshold;

     // 核心功能函数
     function addAccount() {
        const accountName = document.getElementById('accountName').value.trim();
        if (!accountName) return alert("请输入账号名称");
        
        if (!counters[accountName]) {
            const now = new Date();
            counters[accountName] = {
                count: 0,
                lastUpdated: now.toISOString(),
                history: [{
                    timestamp: now.toISOString(),
                    action: '账号创建',
                    delta: 0,
                    count: 0
                }]
            };
            saveAndRender();
            document.getElementById('accountName').value = '';
        } else {
            alert("该账号已存在");
        }
    }


    // 数据迁移（兼容旧版本）
    Object.keys(counters).forEach(account => {
        if (typeof counters[account] === 'number') {
            counters[account] = {
                count: counters[account],
                lastUpdated: new Date().toISOString(),
                history: [{
                    timestamp: new Date().toISOString(),
                    action: '数据迁移',
                    delta: counters[account],
                    count: counters[account]
                }]
            };
        }
    });

   
    function updateCounter(account, delta) {
        const counter = counters[account];
        const newCount = Math.max(counter.count + delta, 0);
        const now = new Date();
        
        counter.history.push({
            timestamp: now.toISOString(),
            action: delta > 0 ? '增加' : '减少',
            delta: Math.abs(delta),
            count: newCount
        });
        
        counter.count = newCount;
        counter.lastUpdated = now.toISOString();
        saveAndRender();
    }

    // 安全清除功能
    function getYesterdayDate() {
        const date = new Date();
        date.setDate(date.getDate() - 1);
        return [
            date.getFullYear(),
            (date.getMonth() + 1).toString().padStart(2, '0'),
            date.getDate().toString().padStart(2, '0')
        ].join('-');
    }

    // 计数清零
    function resetAllCounters() {
        if (!confirm('⚠️ 即将重置所有账号的计数为0！\n此操作不可撤销，确认继续吗？')) return;
        
        Object.keys(counters).forEach(account => {
            const counter = counters[account];
            const now = new Date();
            counter.history.push({
                timestamp: now.toISOString(),
                action: '计数器重置',
                delta: counter.count,
                count: 0
            });
            counter.count = 0;
            counter.lastUpdated = now.toISOString();
        });
        
        saveAndRender();
        alert('✅ 所有账号计数已成功归零！');
    }

    // 单个按钮删除功能
    function deleteCounter(account) {
        if (!confirm(`确定要永久删除 "${account}" 的计数器吗？\n该操作不可撤销！`)) return;
        
        delete counters[account];
        saveAndRender();
        alert(`已成功删除计数器：${account}`);
    }

    // 数据持久化
    function saveAndRender() {
        localStorage.setItem('chatCounters', JSON.stringify(counters));
        renderCounters();
        updateStatistics();
    }

    // 统计更新函数
    function updateStatistics() {
        const stats = calculateStats();
        
        document.getElementById('totalCount').textContent = stats.total;
        const compElement = document.getElementById('compensationValue');
        compElement.textContent = stats.compensation;
        compElement.className = `performance-value ${stats.compensation > 0 ? 'good' : ''}`;
        
        const containerElement = document.getElementById('containerValue');
        containerElement.textContent = stats.containerValue;
        containerElement.className = `performance-value ${stats.containerValue >= 100 ? 'good' : 'bad'}`;
    }

    // 统计计算函数
    function calculateStats() {
        const threshold = parseInt(document.getElementById('thresholdInput').value) || 100;
        let total = 0;
        let compensation = 0;
        let allReached = true;

        Object.values(counters).forEach(counter => {
            const count = Number(counter.count) || 0;
            total += count;
            
            if (count > threshold) {
                compensation += count - threshold;
            }
            
            if (count < threshold) {
                allReached = false;
            }
        });

        const containerValue = allReached ? 100 + compensation : -100;
        
        return {
    total: total,
    compensation: compensation,
    containerValue: containerValue
};
        };

        // 清除所有数据
        function handleClearAll() {
            if (!confirm('⚠️ 此操作将永久删除所有数据！\n确认要继续吗？')) return;

            const requiredDate = getYesterdayDate();
            const userInput = prompt(`请输入昨日日期（格式：${requiredDate}）以确认清除操作：`);

            if (userInput === requiredDate) {
                localStorage.removeItem('chatCounters');
                counters = {};
                renderCounters();
                alert('✅ 所有数据已成功清除！');
            } else {
                alert('❌ 日期验证失败，清除操作已取消');
            }
        }
    

        // 渲染计数器
        function renderCounters() {
    const countersContainer = document.getElementById('countersContainer');
    countersContainer.innerHTML = ''; // 清空现有计数器

    Object.entries(counters).forEach(([account, data]) => {
        const counterElement = document.createElement('div');
        counterElement.className = 'counter-card';

        counterElement.innerHTML = `
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h3 style="margin: 0;">${account}</h3>
                <div>
                    <small style="margin-right: 16px;">最后更新：${new Date(data.lastUpdated).toLocaleString()}</small>
                    <button class="delete-btn" onclick="deleteCounter('${account}')">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </div>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center">
                <div class="count-display">${data.count}</div>
                <div class="control-group">
                    <button class="control-btn minus-btn" onclick="updateCounter('${account}', -1)">
                        <i class="fas fa-minus"></i>
                    </button>
                    <button class="control-btn plus-btn" onclick="updateCounter('${account}', 1)">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
            </div>
        `;

        countersContainer.appendChild(counterElement);
    });
}
    // 阈值输入监听
    document.getElementById('thresholdInput').addEventListener('input', function() {
        const newThreshold = parseInt(this.value);
        if (!isNaN(newThreshold)) {
            currentThreshold = newThreshold;
            localStorage.setItem('chatThreshold', newThreshold);
            updateStatistics();
        }
    });

    // 回车键支持
    document.getElementById('accountName').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            addAccount();
        }
    });

    // 页面加载完成时执行
    window.onload = function() {
        renderCounters();
        updateStatistics();
    };
</script>
</body>
</html>